package com.data.csv.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


@Configuration
public class DataSourceConfig {

    @Value("${customize.decrypt.key:#{null}}")
    private String decryptKey;

    @Value("${customize.decrypt.enabled:false}")
    private String enabled;

    protected <T> T createDataSource(DataSourceProperties properties, Class<? extends DataSource> type) throws Exception {

        String encryptUserName = "";
        String encryptPassword = "";

        if (Boolean.valueOf(enabled).booleanValue()) {
            encryptUserName = AesEncryption.aesDecodeStr(properties.determineUsername(), this.decryptKey);
            encryptPassword = AesEncryption.aesDecodeStr(properties.determinePassword(), this.decryptKey);
        } else {
            encryptUserName = properties.determineUsername();
            encryptPassword = properties.determinePassword();
        }

        DataSourceBuilder builder = DataSourceBuilder.create(properties.getClassLoader()).type(properties.getType()).driverClassName(properties.determineDriverClassName())
                .url(properties.determineUrl()).username(encryptUserName).password(encryptPassword);

        return (T) builder.type(type).build();
    }

    @Bean
    public DataSource dataSource(DataSourceProperties properties) throws Exception {
        DruidDataSource dataSource = createDataSource(properties, DruidDataSource.class);
        return dataSource;
    }
}

